from areas.models import Areas
from django.views import View
from django import http
from django.core.cache import cache


class ProvinceAreasView(View):

    def get(self, request):
        """提供省级地区数据
           1.查询省级数据
           2.序列化省级数据
           3.响应省级数据
           """
        province_list = cache.get('province_list')

        if not province_list:
            try:
                provinces = Areas.objects.filter(parent=None)
            except Exception as e:
                return http.JsonResponse({
                    'code': 400,
                    'errmsg': '服务器内部错误'
                })
            province_list = []

            for province in provinces:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })

            cache.set('province_list',province_list,3600)

        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'province_list': province_list
        })

# 获取子级行政区信息 ++
class SubAreasView(View):
    def get(self, reques, pk):
        """提供市或区地区数据
            1.查询市或区数据
            2.序列化市或区数据
            3.响应市或区数据
            """
        # 读取数据
        sub_data = cache.get(f'sub_areas_{pk}')

        if not sub_data:
            try:
                parent = Areas.objects.get(pk=pk)
                subs = parent.subs.all()
            except Exception as e:
                return http.JsonResponse({
                    'code': 400,
                    'errmsg': '服务器内部错误'
                })
            subs_list = []

            for sub in subs:
                subs_list.append({
                    'id': sub.id,
                    'name': sub.name
                })

            # 构建响应参数
            sub_data = {
                'id': parent.id,
                'name': parent.name,
                'subs': subs_list
            }

            cache.set(f'sub_areas_{parent.id}',sub_data,3600)
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'sub_data': sub_data
        })
